package <#if isCloudModel>${cloudSysEngName}<#else>${packageName}</#if>.config.mutidatasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 动态数据源切面（order 必须要设置，否则事务的切面会优先执行，数据源已经设置完了，再设置就无效了）
 * @author zrx
 */
@Aspect
@Component
@Order(1)
public class DynamicDataSourceAspect {

	private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

	@Before("@annotation(dbType)")
	public void changeDataSourceType(JoinPoint joinPoint, DBType dbType) {
		DataSourceType curType = dbType.value();
		if (!DynamicDataSourceHolder.containsType(curType)) {
			logger.info("指定数据源[{}]不存在，使用默认数据源-> {}", dbType.value(), joinPoint.getSignature());
		} else {
			logger.info("use datasource {} -> {}", dbType.value(), joinPoint.getSignature());
			DynamicDataSourceHolder.setType(dbType.value());
		}

	}

	@After("@annotation(dbType)")
	public void restoreDataSource(JoinPoint joinPoint, DBType dbType) {
		logger.info("use datasource {} -> {}", dbType.value(), joinPoint.getSignature());
		DynamicDataSourceHolder.clearType();
	}

}
